package common

import (
	"GoTime/models"
	"GoTime/utils/cache"
	"time"

	"github.com/gin-gonic/gin"
)

const (
	ctxKeyUser  = "CtxKeyUser"
	ctxKeyToken = "ctxKeyToken"
)

// SetCtxStudent JWT 存储学员信息到 context
func SetCtxStudent(context *gin.Context, id *int) {
	context.Set(ctxKeyUser, id)
}

// GetCtxUser JWT 从context中获取JWT 学员信息
func GetCtxUser(context *gin.Context) (*models.User, bool) {
	if context == nil {
		panic("can not get context value from nil")
	}

	value, exist := context.Get(ctxKeyUser)
	if !exist {
		return nil, false
	}

	meta, exist := value.(*models.User)
	return meta, exist
}

func GetCtxToken(context *gin.Context) (string, bool) {
	if context == nil {
		return "", false
	}

	token := context.GetString(ctxKeyToken)
	return token, len(token) > 0
}

func SetCtxToken(context *gin.Context, token string) {
	if context == nil {
		return
	}

	context.Set(ctxKeyToken, token)
}

func BlockCtxToken(context *gin.Context) {
	token, has := GetCtxToken(context)
	if has {
		cache.SharedRedis().SetString(token, "", int((time.Duration(24) * time.Hour).Seconds()))
	}
}
